package com.k8.common.executor.threadPool;

import com.k8.rpc.url.URL;

import java.util.concurrent.*;

import static com.k8.common.constants.CommonConstants.DISCARD_OLDEST_REJECT;
import static com.k8.common.constants.CommonConstants.DISCARD_REJECT;
import static com.k8.common.constants.CommonKeyConstants.MAX_THREAD_COUNT_KEY;
import static com.k8.common.constants.CommonKeyConstants.REJECT_POLICY_KEY;
import static com.k8.common.executor.NamedThreadFactory.USER_THREAD_FACTORY;

public class FixedThreadPool extends AbstractThreadPool {
    @Override
    protected ExecutorService doGetExecutor(URL url, int core, int max, int limit) {
        BlockingQueue<Runnable> blockingQueue = getBlockingQueue(url);
        String reject = url.getParameter(REJECT_POLICY_KEY);
        if (reject != null) {
            if (DISCARD_REJECT.equals(reject)) {
                return new ThreadPoolExecutor(max, max, 0, TimeUnit.MILLISECONDS, blockingQueue, USER_THREAD_FACTORY, new ThreadPoolExecutor.DiscardPolicy());
            } else if (DISCARD_OLDEST_REJECT.equals(reject)) {
                return new ThreadPoolExecutor(max, max, 0, TimeUnit.MILLISECONDS, blockingQueue, USER_THREAD_FACTORY, new ThreadPoolExecutor.DiscardOldestPolicy());
            }
        }
        return new ThreadPoolExecutor(max, max, 0, TimeUnit.MILLISECONDS, blockingQueue, USER_THREAD_FACTORY);
    }
}
